<?php
namespace app\api\controller;
use app\common\controller\Base;
use think\Db;
/**
 * 一般不需要登录的接口
 */
class Index extends Base{

    /**
     * [index ]
     * @return [type] [description]
     */
    public function index(){
        if(!isset($this->post['lng']) || !isset($this->post['lat'])){
            $this->apiReturn(0,'请上传定位');
        }

        $map = $where =  $having = '';
        //获取指定范围的数据
        $fanwei = db('web_config')->where('key','map_fanwei')->value('value');
        //缩小范围误差
       /* $having = 'juli <= '.$fanwei;*/

        $coord = get_coord(trim($this->post['lng']),trim($this->post['lat']),$fanwei);
      
        $user_validate = $map = $where .= 'lng between '.$coord['left_top']['lng'].' and '.$coord['right_bottom']['lng'].' and lat between '.$coord['right_bottom']['lat'].' and '.$coord['left_top']['lat'];

        //会员登录之后红包做筛选
        if(isset($this->post['token']) && trim($this->post['token']) !== ''){
            $this->user_check(trim($this->post['token']));
            $user_info = db('user')->where('id',UID)->find();
            //性别 不要求或和当前用户性别一样
            $where .= ' and r.sex in (0,'.$user_info['sex'].')';
            //年龄要求
            $where .= ' and ((min_age = 0 && max_age = 0) or (min_age = 0 && max_age <= '.$user_info['age'].') or (min_age <= '.$user_info['age'].' and max_age = 0) or (min_age <= '.$user_info['age'].' and max_age >= '.$user_info['age'].'))';
            //职业
       
            $where .= ' and r.zhiye in (0,'.$user_info['zhiye'].')';
            $user_id = UID;
         
        }else{
            $user_id = 0;
        }
       
        //服务类型
        if(isset($this->post['type']) && in_array(intval($this->post['type']),[1,2])){
            $type = 'type = '.intval($this->post['type']);
            $map .= $map == '' ? $type : ' and '.$type;
        }
        //性别筛选
        if(isset($this->post['sex']) && in_array(intval($this->post['sex']),[1,2])){
            $sex = 'sex = '.intval($this->post['sex']);
            $map .= $map == '' ? $sex : ' and '.$sex;
        }

        //年龄筛选
        if(isset($this->post['min_age']) && isset($this->post['max_age']) && intval($this->post['min_age']) && intval($this->post['max_age'])){
            //年龄对调
            if(intval($this->post['min_age']) > intval($this->post['max_age'])){
                $age = intval($this->post['min_age']);
                $this->post['min_age'] = intval($this->post['max_age']);
                $this->post['max_age'] = $age;
            }
        }
        if(isset($this->post['min_age']) && intval($this->post['min_age'])){
            $min_age = ' age >= '.intval($this->post['min_age']);
            $map .= $map == '' ? $min_age : ' and '.$min_age;
        }
        if(isset($this->post['max_age']) && intval($this->post['max_age'])){
            $max_age = ' age <= '.intval($this->post['max_age']);
            $map .= $map == '' ? $max_age : ' and '.$max_age;
        }

        //行业
        if(isset($this->post['hangye']) && intval($this->post['hangye'])){
            $hangye = intval($this->post['hangye']);
            $map .= $map == '' ? $hangye : ' and '.$hangye;
        }
      

        $this->apiReturn(1,'列表',[
            'need' => model('common/need')->needByMap($map,trim($this->post['lng']),trim($this->post['lat']),$having),
            'service' => model('common/service')->serviceByMap($map,trim($this->post['lng']),trim($this->post['lat']),$having),
            'red' => model('common/red_packet')->redByMap($where,trim($this->post['lng']),trim($this->post['lat']),$having),
            'coupon' =>  model('common/coupon')->couponByMap($where,trim($this->post['lng']),trim($this->post['lat']),$having),
            'user' => model('common/user')->userByMap($user_validate,trim($this->post['lng']),trim($this->post['lat']),$having,$user_id)
        ]);
    }
   

   

    /**
     * [手机号注册]
     * @return [type] [description]
     */
    public function register(){
        $rule = [
            'account' => 'require|regex:/^1[345789]{1}\d{9}$/',
            'password' => 'require|alphaNum|length:6,16',
            'code' => 'require',
            'nick_name' => 'max:10',
            'sex' => 'in:1,0,2',
            'birthday' => 'dateFormat:Y-m-d',
        ];
        $msg = [
            'account.require' => '请输入手机号',
            'account.regex' => '手机号格式错误',
            'password.require' => '请输入登录密码',
            'password.alphaNum' => '登录密码只能是数字或字母',
            'password.length' => '登录密码长度为6至16个字符',
            'code.require' => '请输入验证码',
            'nick_name.max' => '昵称限制为10个字符',
            'sex.in' => '性别有误',
            'birthday.dateFormat' => '生日格式错误'
        ];

        $validate = new \think\Validate($rule,$msg);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        //职业
        if(isset($this->post['zhiye']) && $this->post['zhiye']){
            $zhiye_info = db('zhiye')->where('id',$this->post['zhiye'])->find();
            if(!$zhiye_info){
                $this->apiReturn(0,'该职业不存在');
            }
            $this->post['hangye'] = $zhiye_info['hangye'];
        }   
        //该手机是否注册
        $res = model('common/user')->getUserInfo(['account'=>$this->post['account']]);
        if($res){
            $this->apiReturn(0,'该手机号已经注册，请直接登录');
        }
        
        $code_check = model('common/send_code')->checkCode($this->post['account'],$this->post['code'],1);

        if($code_check['status'] == 0){
            $this->apiReturn(0,$code_check['msg']);
        }
        $this->post['last_login_time'] = time();
        $this->post['register_type'] = 1;
        $this->post['password'] = md5($this->post['password']);
        
        if(!model('common/user')->allowField(true)->save($this->post)){

            $this->apiReturn(0,'注册失败，请稍后再试');
        }
 
        $this->apiReturn(1,'注册成功',model('common/user')->getUserInfo(['account'=>$this->post['account']]));
    }


    /**
     * [手机号登录]
     * @return [type] [description]
     */
    public function login(){
        $rule = [
            'account' => 'require|regex:/^1[345789]{1}\d{9}$/',
            'password' => 'require|alphaNum|length:6,16'
        ];
        $msg = [
            'account.require' => '请输入手机号',
            'account.regex' => '手机号格式错误',
            'password.require' => '请输入登录密码',
            'password.alphaNum' => '登录密码只能是数字或字母',
            'password.length' => '登录密码长度为6至16个字符'

        ];

        $validate = new \think\Validate($rule,$msg);

        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

         //该手机是否注册
        $res = model('common/user')->getUserInfo(['account'=>$this->post['account']]);

        if(is_null($res)){
            $this->apiReturn(0,'该手机号未注册');
        }

        if(md5($this->post['password']) != $res['password']){
            $this->apiReturn(0,'登录密码错误');
        }

        if($res['disabled'] == 0){
            $this->apiReturn(0,'该账号已被禁用，请联系客服');
        }
        $token = time().rand(1000,9999);
        model('common/user')->loginBeforeHandle($res['id'],$token);

        $Aes = new \Aes\Aes();
        $res['token'] = $Aes->aes128cbcEncrypt($token);
        $this->apiReturn(1,'登录成功',$res);
    }

    /**
     * [第三方登录]
     * @return [type] [description]
     */
    public function thirdLogin(){
        $rule = [
            'openid' => 'require',
            'register_type' => 'require|in:2,3',
            'sex' => 'in:1,0,2',
            'birthday' => 'dateFormat:Y-m-d',
        ];
        $msg = [
            'openid.require' => '参数openid丢失',
            'register_type.require' => '请选择注册方式',
            'register_type.in' => '登录方式有误',
            'sex.in' => '性别有误',
            'birthday.dateFormat' => '生日格式错误'
        ];

        $validate = new \think\Validate($rule,$msg);

        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        $res = model('common/user')->getUserInfo(['openid'=>$this->post['openid'],'register_type'=>$this->post['register_type']]);

        if($res){
            if($res['disabled'] == 0){
                $this->apiReturn(0,'该账号已被禁用，请联系客服');
            }
            $token = time().rand(1000,9999);
            model('common/user')->loginBeforeHandle($res['id'],$token);

            $Aes = new \Aes\Aes();
            $res['token'] = $Aes->aes128cbcEncrypt($token);

            $this->apiReturn(1,'登录成功',$res);
        }

        $this->post['last_login_time'] = time();
        
        if(!model('common/user')->allowField(true)->save($this->post)){
           
            $this->apiReturn(0,'登录失败，请稍后再试');
        }
        
        
        $this->apiReturn(1,'登录成功',model('common/user')->getUserInfo(['openid'=>$this->post['openid'],'register_type'=>$this->post['register_type']]));

    }

    //行业列表
    public function hangye(){
        $where = [];
        if(isset($this->post['keywords']) && $this->post['keywords']){
            $where['name'] = ['like','%'.$this->post['keywords'].'%'];
        }
        $list = db('hangye')->where($where)->order('sort desc')->field('id,name')->select();
        $pinyin = new \pinyin\ChineseToPinyin();
        $initial = [];
        foreach($list as $key=>$val){
            $init = substr($pinyin->TransformUcwords($val['name']),0,1);
            if(!$init){
                $init = strtoupper(substr($val['name'],0,1));
            }
           
            $exists_key = array_search($init,array_column($initial,'initial'));

            if($exists_key === false){
                $initial[] = ['initial'=>$init,'hangye'=>[$val]];
            }else{
                $initial[$exists_key]['hangye'][] = $val;
            }
        }
        $inits = array_column($initial,'initial');
        array_multisort($inits,SORT_ASC,$initial);
        $this->apiReturn(1,'行业列表',$initial);
    }

    //不带首字母的行业
    public function hy(){
       
        $list = db('hangye')->order('sort desc')->field('id,name')->select();
        
        $this->apiReturn(1,'行业列表',$list);
    }

    //职业列表
    public function zhiye(){
        $where = [];
        if(isset($this->post['keywords']) && $this->post['keywords']){
            $where['name'] = ['like','%'.$this->post['keywords'].'%'];
        }
        $list = db('zhiye')->where($where)->order('sort desc')->field('id,name')->select();
        $pinyin = new \pinyin\ChineseToPinyin();
        $initial = [];
        foreach($list as $key=>$val){
            $init = substr($pinyin->TransformUcwords($val['name']),0,1);
            if(!$init){
                $init = strtoupper(substr($val['name'],0,1));
            }
           
            $exists_key = array_search($init,array_column($initial,'initial'));

            if($exists_key === false){
                $initial[] = ['initial'=>$init,'hangye'=>[$val]];
            }else{
                $initial[$exists_key]['hangye'][] = $val;
            }
        }
        $inits = array_column($initial,'initial');
        array_multisort($inits,SORT_ASC,$initial);
        $this->apiReturn(1,'职业列表',$initial);
        
    }


    /**
     * [nearby 附近圈、帮主、需求、服务]  待完善
     * @return [type] [description]
     */
    public function nearby(){
        $validate = new \think\validate([
                'type'=>'require|in:1,2,3,4',
                'recom' => 'require|in:0,1',
                'city' => 'require',
                'lng' => 'require',
                'lat' => 'require'
            ],[
                'type.require'=> '参数type丢失',
                'type.in' => '参数type错误',
                'recom.require' => '参数recom丢失',
                'recom.in' => '参数recom错误',
                'city.require' => '参数city丢失',
                'lng.require' => '参数lng丢失',
                'lat.require' => '参数lat丢失'
            ]);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        $where = '';
        //性别筛选
        if(isset($this->post['sex']) && in_array(intval($this->post['sex']),[1,2])){
            $sex = ' sex = '.intval($this->post['sex']);
            $where .= $where == '' ?  $sex : ' and'.$sex ;
        }
        //关键字搜索
        if(isset($this->post['keywords']) && trim($this->post['keywords']) != ''){
            $keywords = ' title like "%'.$this->post['keywords'].'%"';
            $where .= $where == '' ? $keywords : ' and'.$keywords;
        }

        //年龄
        if(isset($this->post['min_age']) && intval($this->post['min_age']) && isset($this->post['max_age']) && intval($this->post['max_age'])){
            if(intval($this->post['min_age']) > intval($this->post['max_age'])){
                $other = intval($this->post['max_age']);
                $this->post['max_age'] = intval($this->post['min_age']);
                $this->post['min_age'] = $other;
            }
        }
        
        if(isset($this->post['min_age']) && intval($this->post['min_age'])){
            $min_age = ' age >= '.intval($this->post['min_age']);
            $where .= $where == '' ? $min_age : ' and'.$min_age;
        }
        if(isset($this->post['max_age']) && intval($this->post['max_age'])){
            $max_age = ' age <= '.intval($this->post['max_age']);
            $where .= $where == '' ? $max_age : ' and'.$max_age;
        }
        //行业筛选
        if(isset($this->post['hangye']) && intval($this->post['hangye'])){
            $hangye = ' hangye = '.intval($this->post['hangye']);
            $where .=  $where == '' ? $hangye : ' and'.$hangye;
        }
        
        if(isset($this->post['token']) && trim($this->post['token']) != ''){
            $this->user_check(trim($this->post['token']));

            $user_id = UID;
            $where .= $where == '' ? ' u.id != '.$user_id : ' and u.id != '.$user_id;
        }else{
            $user_id = 0;
        }


        //需求
        if($this->post['type'] == 1){

            $city = ' city = '.trim($this->post['city']);
            $where .= $where == '' ? $city : ' and'.$city ;
            $end_time = ' end_time >= '.time();
            $where .= $where == '' ? $end_time : ' and'.$end_time ;

            if($this->post['recom']){
                $where .=  $where == '' ? ' grade = 1' : ' and grade = 1';
                $list = model('common/need')->dataCheck(model('common/need')->needList($where,'juli asc,add_time desc',0,trim($this->post['lng']),trim($this->post['lat']),5),$user_id);
            }else{
                $list = model('common/need')->dataCheck(model('common/need')->needList($where,'juli asc,add_time desc',$this->p,trim($this->post['lng']),trim($this->post['lat'])),$user_id);
            }
            
         
        }
        //附近圈
        if($this->post['type'] == 2){
            $from_city = ' from_city = '.trim($this->post['city']);
            $where .= $where == '' ? $from_city : ' and '.$from_city;


            //如果有广告则插入广告
            $ad = db('ad_buy')->alias('a')->join(['bz_user' => 'u'],'u.id = a.user_id')
                ->where('position_id',4)->where('a.status',1)->where('use_num','exp','< buy_num')
                ->where('a.issue_time','elt',time())
                ->order('pay_time asc')
                ->field('u.nick_name,photo_path,a.title,a.image,a.content,a.video')
                ->limit(1)
                ->select();

            if($ad){
                $ad[0]['is_ad'] = 1;
                $ad[0]['image'] = $ad[0]['image'] == '' ? [] : explode(',',$ad[0]['image']);
                $ad[0]['content'] = empty($ad[0]['content']) ? '' : $ad[0]['content'];
                $ad[0]['video'] = empty($ad[0]['video']) ? '' : $ad[0]['video'];

                if($this->p  == 1){
                    $list = model('common/nearby')->dataCheck(model('common/nearby')->nearbyList($where,'juli asc,add_time desc',$this->p,trim($this->post['lng']),trim($this->post['lat']),($this->p-1)*9,9),$user_id);
                    $list = json_decode(json_encode($list),true);
                    $list = array_merge($list,$ad);
                    //如果数组>4条则将广告位置进行调换
                    if(count($list) > 4){
                        $now_data = $list[3];
                        $list[3] = $list[count($list) - 1];
                        $list[count($list) - 1] = $now_data;
                    }
                }else{
                    $list = model('common/nearby')->dataCheck(model('common/nearby')->nearbyList($where,'juli asc,add_time desc',$this->p,trim($this->post['lng']),trim($this->post['lat']),($this->p-2)*config('page_size') + 9,config('page_size')),$user_id);

                }
            }else{
                $list = model('common/nearby')->dataCheck(model('common/nearby')->nearbyList($where,'juli asc,add_time desc',$this->p,trim($this->post['lng']),trim($this->post['lat'])),$user_id);
            }
            
            
        }

        //服务
        if($this->post['type'] == 3){
            $from_city = ' from_city = '.trim($this->post['city']);
            $where .= $where == '' ? $from_city : ' and '.$from_city;

            if($this->post['recom']){
                $where .=  $where == '' ? ' grade = 1' : ' and grade = 1';
                $list = model('common/service')->dataCheck(model('common/service')->serviceList($where,'juli asc,add_time desc',0,trim($this->post['lng']),trim($this->post['lat']),5),$user_id);
            }else{
                $list = model('common/service')->dataCheck(model('common/service')->serviceList($where,'juli asc,add_time desc',$this->p,trim($this->post['lng']),trim($this->post['lat'])),$user_id);
            }
            
        }

        //附近帮主
        if($this->post['type'] == 4){
            $from_city = ' from_city = '.trim($this->post['city']);
            $where .= $where == '' ? $from_city : ' and '.$from_city;
            if($this->post['recom']){

                $where .=  $where == '' ? ' grade = 1' : ' and grade = 1';

                $list = model('common/user')->userList($where,'juli asc,register_time desc',0,trim($this->post['lng']),trim($this->post['lat']),5);
            }else{
                $list = model('common/user')->userList($where,'juli asc,register_time desc',$this->p,trim($this->post['lng']),trim($this->post['lat']));
            }
            

        }
        $this->apiReturn(1,'列表',$list);
    }


    //指定用户发布信息
    public function userIssue(){
        $validate = new \think\validate([
                'type'=>'require|in:1,2,3,4',
                'user_id' => 'require',
                'lng' => 'require',
                'lat' => 'require'
            ],[
                'type.require'=> '参数type丢失',
                'type.in' => '参数type错误',
                'user_id.require' => '参数user_id丢失',
                'lng.require' => '参数lng丢失',
                'lat.require' => '参数lat丢失'
            ]);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        if(isset($this->post['token']) && trim($this->post['token']) != ''){
            $this->user_check(trim($this->post['token']));
            $user_id = UID;
        }else{
            $user_id = 0;
        }

        //需求
        if($this->post['type'] == 1){
            $model = model('common/need');
            $list = $model->dataCheck($model->needList(['n.user_id' => intval($this->post['user_id'])],'n.add_time desc',$this->p,trim($this->post['lng']),trim($this->post['lat'])),$user_id);
    
        }

        //日记
        if($this->post['type'] == 2){
            $model = model('common/nearby');
            $list = $model->dataCheck($model->nearbyList(['n.user_id' => intval($this->post['user_id'])],'n.add_time desc',$this->p,trim($this->post['lng']),trim($this->post['lat'])),$user_id);
        }

        //服务
        if($this->post['type'] == 3){
            $model = model('common/service');
            $list = $model->dataCheck($model->serviceList(['s.user_id' => intval($this->post['user_id'])],'s.add_time desc',$this->p,trim($this->post['lng']),trim($this->post['lat'])),$user_id);
        }
        //个人资料
        if($this->post['type'] == 4){
            $list = db('user')->where('id',intval($this->post['user_id']))->field('tag,intro,cia,sale')->find();
            $list['tag'] = $list['tag'] == '' ? [] : explode(',',$list['tag']);
            $list['cia'] = empty($list['cia']) ? [] : explode(',',$list['cia']);
        }
        $this->apiReturn(1,'列表',$list);
    }


    /**
     * [userHome 个人主页]
     * @return [type] [description]
     */
    public function userHome(){
        if(!isset($this->post['user_id']) || intval($this->post['user_id']) <= 0){
            $this->apiReturn(0,'参数user_id丢失');
        }

        $info = model('common/user')->getUserInfo(['id' => intval($this->post['user_id'])],'bg,nick_name,photo_path,kaopu,service_count,care_num,fans_num,sex,tag,sign');

        if(is_null($info)){
            $this->apiReturn(0, '该会员不存在');
        }

        if(isset($this->post['token']) && trim($this->post['token']) != ''){

            $this->user_check(trim($this->post['token']));

            if(UID != intval($this->post['user_id'])){
                $res = db('visiter')->where('visit',UID)->where(
                    [
                        'add_time' => [
                            ['egt',strtotime(date('Ymd'))],
                            ['lt',strtotime(date('Ymd').'+1 day')]
                        ]
                    ]
                )->find();
                if(!$res){
                    db('visiter')->insert([
                        'user_id' => intval($this->post['user_id']),
                        'visit' => UID,
                        'add_time' => time()
                    ]);
                }
            }
        }
        
        $info['visit_count'] = db('visiter')
            ->where('user_id',intval($this->post['user_id']))
            ->where(
                    [
                        'add_time' => [
                            ['egt',strtotime(date('Ymd'))],
                            ['lt',strtotime(date('Ymd').'+1 day')]
                        ]
                    ]
                )
            ->count();
        $this->apiReturn(1,'信息',$info);
    }


    /**
     * [city 城市列表]
     * @return [type] [description]
     */
    public function city(){
        $model = db('area')->field('id,name')->where('arealevel',2);
        if(isset($this->post['keywords']) && trim($this->post['keywords']) !== ''){
            $model->where('name','like','%'.trim($this->post['keywords']).'%');
        }
        $list = $model->select();
        $pinyin = new \pinyin\ChineseToPinyin();
        $initial = [];
        foreach($list as $key => $val){
            if($val['id'] == '500000'){
                $init = 'C';
            }else{
                $init = substr($pinyin->TransformUcwords($val['name']),0,1);
                if(!$init){
                    $init = strtoupper(substr($val['name'],0,1));
                }
            }
            $exists_key = array_search($init,array_column($initial,'initial'));

            if($exists_key === false){
                $initial[] = ['initial'=>$init,'city'=>[$val]];
            }else{
                $initial[$exists_key]['city'][] = $val;
            }
        }
        $inits = array_column($initial,'initial');
        array_multisort($inits,SORT_ASC,$initial);
        $this->apiReturn(1,'城市列表',$initial);
    }


    //关于我们
    public function about(){
        $value = db('web_config')->where('key','about')->value('value');
        $this->view->engine->layout(false);
        return $this->fetch('',['value' => $value]);
    }

    //会员价格列表展示
    public function  gradePrice(){
        $list = db('grade')->select();
        $this->apiReturn(1,'',$list);
    }

    //会员权益
    public function quanyi(){
        $this->apiReturn(1,'会员权益',['quanyi'=>db('web_config')->where('key','h_quanyi')->value('value')]);
    }
}
